package algorithm_demo.sort;

/**
 * 求小和问题
 * 在一个数组中，每一个树左边比当前数小的数累加起来，叫做这个数组的小和。
 * 归并排序为基础
 * @author Api
 * @date 2023/1/24 1:26
 */
public class SmallSum {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 3, 2, 3};//1+1+2+1+3+2+3+1+3+2+3+4+1+2+1
        int i = smallSum(arr);
        System.out.println(i);
    }


    public static int smallSum(int[] arr) {
        if (arr == null || arr.length < 2) {
            return 0;
        }
        return process(arr, 0, arr.length - 1);
    }


    public static int process(int[] arr, int L, int R) {
        if (L == R) {
            return 0;
        }
        int mid = L + ((R - L) >> 1);
        //左侧排序的并且求小和的数量+右侧排序的并且求小和的数量+左侧排好和右侧排好产生小和的数量
        return process(arr, L, mid) + process(arr, mid + 1, R) + merge(arr, L, mid, R);
    }


    public static int merge(int[] arr, int L, int mid, int R) {
        int[] help = new int[R - L + 1];
        int i = 0;
        int p1 = L;
        int p2 = mid + 1;
        int res = 0;
        while (p1 <= mid && p2 <= R) {
            res += arr[p1] < arr[p2] ? (R - p2 + 1) * arr[p1] : 0;
            help[i++] = arr[p1] < arr[p2] ? arr[p1++] : arr[p2++];
        }
        while (p1 <= mid) {
            help[i++] = arr[p1++];
        }
        while (p2 <= R) {
            help[i++] = arr[p2++];
        }
        for (i = 0; i < help.length; i++) {
            arr[L + i] = help[i];
        }
        return res;
    }
}
